package com.lnsf.bookstore.web.cart.controller;

import com.alibaba.fastjson.JSONObject;
import com.lnsf.bookstore.common.annotation.IgnoreAuth;
import com.lnsf.bookstore.common.annotation.LoginUser;
import com.lnsf.bookstore.common.controller.ApiBaseAction;
import com.lnsf.bookstore.web.address.service.ApiAddressService;
import com.lnsf.bookstore.web.address.vo.ApiAddress;
import com.lnsf.bookstore.web.book.service.ApiBookService;
import com.lnsf.bookstore.web.book.vo.ApiBook;
import com.lnsf.bookstore.web.bookSpecification.service.ApiBookSpecificationService;
import com.lnsf.bookstore.web.bookSpecification.vo.ApiBookSpecification;
import com.lnsf.bookstore.web.cart.service.ApiCartService;
import com.lnsf.bookstore.web.cart.vo.ApiCart;
import com.lnsf.bookstore.web.coupon.service.ApiCouponService;
import com.lnsf.bookstore.web.coupon.vo.ApiCoupon;
import com.lnsf.bookstore.web.user.vo.ApiUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/cart")
public class ApiCartController extends ApiBaseAction{
    @Autowired
    private ApiCartService apiCartService;
    @Autowired
    private ApiBookService apiBookService;
    @Autowired
    private ApiBookSpecificationService apiBookSpecificationService;
    @Autowired
    private ApiAddressService apiAddressService;
    @Autowired
    private ApiCouponService apiCouponService;

    @RequestMapping("getCart")
    @ResponseBody
    //@IgnoreAuth
    public Object getCart(@LoginUser ApiUser loginUser) {
        Map<String, Object> resultObj = new HashMap();

        //查询列表数据
        Map param = new HashMap();
       // param.put("userId", loginUser.getUserId());
       param.put("userId", loginUser.getUserId());
        List<ApiCart> cartList = apiCartService.queryList(param);
        //获取购物车统计信息
        Integer bookCount = 0;
        BigDecimal bookAmount = new BigDecimal(0.00);
        Integer checkedBookCount = 0;
        BigDecimal checkedBookAmount = new BigDecimal(0.00);
        for (ApiCart cartItem : cartList) {
            bookCount += cartItem.getNumber();
            bookAmount = bookAmount.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber())));
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                checkedBookCount += cartItem.getNumber();
                checkedBookAmount = checkedBookAmount.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber())));
            }
        }

        resultObj.put("cartList", cartList);
        Map<String, Object> cartTotal = new HashMap();
        cartTotal.put("bookCount", bookCount);
        cartTotal.put("bookAmount", bookAmount);
        cartTotal.put("checkedBookCount", checkedBookCount);
        cartTotal.put("checkedBookAmount", checkedBookAmount);
        //
        resultObj.put("cartTotal", cartTotal);
        return resultObj;
    }

    /**
     * 获取购物车信息，所有对购物车的增删改操作，都要重新返回购物车的信息
     */
    @ResponseBody
    @RequestMapping("index")
    public Object index(@LoginUser ApiUser loginUser) {
        return toResponsSuccess(getCart(loginUser));
    }




    /**
     * 是否选择商品，如果已经选择，则取消选择，批量操作
     */
    @RequestMapping("checked")
    //@IgnoreAuth
    @ResponseBody
    public Object checked(@LoginUser ApiUser loginUser) {
        JSONObject jsonParam = getJsonRequest();
        String bookIds = jsonParam.getString("bookIds");
        Integer isChecked = jsonParam.getInteger("isChecked");
        if (StringUtils.isBlank(bookIds)) {
            return this.toResponsFail("删除出错");
        }
        String[] bookIdArray = bookIds.split(",");
        apiCartService.updateCheck(bookIdArray, isChecked, loginUser.getUserId());
        return toResponsSuccess(getCart(loginUser));
    }


    //删除选中的购物车商品，批量删除
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(@LoginUser ApiUser loginUser) {
        Integer userId = loginUser.getUserId();

        JSONObject jsonObject = getJsonRequest();
        String bookIds = jsonObject.getString("bookIds");

        if (StringUtils.isBlank(bookIds)) {
            return toResponsFail("删除出错");
        }
        String[] bookIdsArray = bookIds.split(",");
        int[] bookIdss = new int[bookIdsArray.length];
        for (int i = 0; i <bookIdsArray.length; i++){
            bookIdss[i]= Integer.parseInt(bookIdsArray[i]);
        }
        apiCartService.deleteByUserAndBookIds(userId, bookIdss);

        return toResponsSuccess(getCart(loginUser));
    }

    /**
     * 更新指定的购物车信息,更新数量
     */
    @RequestMapping("update")
    @ResponseBody
    public Object update(@LoginUser ApiUser loginUser) {
        JSONObject jsonParam = getJsonRequest();
        Integer bookId = jsonParam.getInteger("bookId");
        String bookSpecifitionIds = jsonParam.getString("bookSpecifitionIds");
        Integer number = jsonParam.getInteger("number");
        Integer id = jsonParam.getInteger("id");
        //取得规格的信息,判断规格库存
        String str[] = bookSpecifitionIds.split("_");
        for(String bookSpecifitionId : str){
            ApiBookSpecification apiBookSpecification = apiBookSpecificationService.queryObject(bookSpecifitionId);
            if (null == apiBookSpecification || apiBookSpecification.getNum() < number) {
                return this.toResponsObject(400, apiBookSpecification.getName()+":"+apiBookSpecification.getValue()+"库存不足", "");
            }
        }

        //判断是否已经存在bookId购物车商品
        ApiCart cartInfo = apiCartService.queryObject(id);
        //只是更新number
        if (cartInfo.getBookId().equals(bookId)) {
            cartInfo.setNumber(number);
            apiCartService.update(cartInfo);
            //立刻找到全部购物车数据
            return toResponsSuccess(getCart(loginUser));
        }
        return toResponsSuccess(getCart(loginUser));
    }

    //  获取购物车商品的总件件数
    @RequestMapping("bookCount")
    @ResponseBody
    public Object bookCount(@LoginUser ApiUser loginUser) {
        if (null == loginUser || null == loginUser.getUserId()) {
            return toResponsFail("未登录");
        }
        Map<String, Object> resultObj = new HashMap();
        //查询列表数据
        Map param = new HashMap();
        param.put("userId", loginUser.getUserId());
        List<ApiCart> cartList = apiCartService.queryList(param);
        //获取购物车统计信息
        Integer bookCount = 0;
        for (ApiCart cartItem : cartList) {
            bookCount += cartItem.getNumber();
        }
        resultObj.put("cartList", cartList);
        //bookCount
        Map<String, Object> cartTotal = new HashMap();
        cartTotal.put("bookCount", bookCount);
        //cartList、cartTotal
        resultObj.put("cartTotal", cartTotal);
        return toResponsSuccess(resultObj);
    }

    /**
     * 订单提交前的检验和填写相关订单信息
     */
    @RequestMapping("checkout")
    @ResponseBody
    public Object checkout(@LoginUser ApiUser loginUser, Integer couponId, Map bookInfo, Integer addressId) {
        Map<String, Object> resultObj = new HashMap();

        //根据收货地址计算运费
        BigDecimal freightPrice = new BigDecimal(10.00);
        //获取用户收获地址
        Map map = new HashMap();
        ApiAddress apiAddressEntity = null;
        if(addressId!=null){
            map.put("addressId",addressId);
        }
        map.put("userId",loginUser.getUserId());
        List<ApiAddress> apiAddressList = apiAddressService.queryByUid(map);
        /*for(ApiAddress apiAddress : apiAddressList){
            if(apiAddress.getChecked() == 1){
                apiAddressEntity = apiAddress;
            }
        }*/
        if(apiAddressList.size()!=0){
            resultObj.put("address",apiAddressList.get(0));
        }else {
            resultObj.put("address","");
        }

        //获取要购买的商品
        Map<String, Object> cartData = (Map<String, Object>) this.getCart(loginUser);

        List<ApiCart> checkedBooksList = new ArrayList();
        for (ApiCart cartEntity : (List<ApiCart>) cartData.get("cartList")) {
            if (cartEntity.getChecked() == 1) {
                checkedBooksList.add(cartEntity);
            }
        }

        //获取可用的优惠券信息
        Map usercouponMap = new HashMap();
        usercouponMap.put("userId", loginUser.getUserId());
        List<ApiCoupon> couponList = apiCouponService.queryUserCouponList(usercouponMap);
        ApiCoupon checkedCoupon = null;
        BigDecimal couponPrice = new BigDecimal(0.00);  //使用优惠券减免的金额
        if (null != couponList && couponList.size() > 0) {
            for (ApiCoupon couponVo : couponList) {
                if (null != couponId && couponId.equals(couponVo.getId())) {
                    couponPrice = couponVo.getParPrice();
                    checkedCoupon = couponVo;
                }
            }
        }

        //计算订单的费用
        //商品总价
        BigDecimal booksTotalPrice = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedBookAmount");
        //订单的总价
        BigDecimal orderTotalPrice = booksTotalPrice.add(freightPrice);
        //实际金额
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);  //减去其它支付的金额后，要实际支付的金额
        resultObj.put("freightPrice", freightPrice);    //运费金额
        resultObj.put("couponList", couponList);//优惠券列表
        resultObj.put("couponPrice", couponPrice);//选中的优惠券金额
        resultObj.put("checkedBooksList", checkedBooksList);//选中的商品
        resultObj.put("booksTotalPrice", booksTotalPrice);//商品总金额
        resultObj.put("orderTotalPrice", orderTotalPrice);//订单总金额
        resultObj.put("actualPrice", actualPrice);//实际总金额
        //resultObj.put("address", apiAddressEntity);//实际总金额
        return toResponsSuccess(resultObj);
    }

    /**
     * 选择优惠券列表
     */
    @RequestMapping("checkedCouponList")
    @ResponseBody
    public Object checkedCouponList(@LoginUser ApiUser loginUser) {
        //
        Map param = new HashMap();
        param.put("userId", loginUser.getUserId());
        List<ApiCoupon> couponVos = apiCouponService.queryUserCouponList(param);
        if (null != couponVos && couponVos.size() > 0) {
            // 获取要购买的商品
            Map<String, Object> cartData = (Map<String, Object>) this.getCart(loginUser);
            List<ApiCart> checkedBooksList = new ArrayList();
            List<Integer> checkedBooksIds = new ArrayList();
            for (ApiCart cartEntity : (List<ApiCart>) cartData.get("cartList")) {
                if (cartEntity.getChecked() == 1) {
                    checkedBooksList.add(cartEntity);
                    checkedBooksIds.add(cartEntity.getId());
                }
            }
            // 计算订单的费用
            BigDecimal booksTotalPrice = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedBookAmount");  //商品总价
            // 如果没有用户优惠券直接返回新用户优惠券
            for (ApiCoupon couponVo : couponVos) {
                //满足的最大金额如果小于订单总金额就不能用
                if (couponVo.getMaxPrice().compareTo(booksTotalPrice) <= 0) {
                    couponVo.setEnabled(1);
                }
            }
        }
        return toResponsSuccess(couponVos);
    }


    private String[] getSpecificationIdsArray(String ids){
        String[] idsArray = null;
        if (org.apache.commons.lang.StringUtils.isNotEmpty(ids)){
            String[] tempArray = ids.split("_");
            if (null != tempArray && tempArray.length > 0){
                idsArray = tempArray;
            }
        }
        return idsArray;
    }


    /**
     * 添加商品到购物车
     */
    @RequestMapping("add")
    @ResponseBody
    public Object add(@LoginUser ApiUser loginUser) {
        JSONObject jsonParam = getJsonRequest();
        Integer bookId = jsonParam.getInteger("bookId");
        List<ApiBookSpecification> apiBookSpecificationList = jsonParam.getJSONArray("specificationInfo").toJavaList(ApiBookSpecification.class);
        Integer number = jsonParam.getInteger("num");

        //判断商品是否可以购买
        ApiBook apiBook = apiBookService.queryObject(bookId);
        //判断购物车中是否存在此规格商品
        Map cartParam = new HashMap();
        cartParam.put("bookId", bookId);
        cartParam.put("userId", loginUser.getUserId());
        List<ApiCart> cartInfoList = apiCartService.queryList(cartParam);
        ApiCart cartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        if (null == cartInfo) {
            //添加操作
            //添加规格名和值
            String[] bookSepcifitionValue = null;
            String[] bookSepcifitionId = null;
            bookSepcifitionId = new String [apiBookSpecificationList.size()];
            bookSepcifitionValue = new String [apiBookSpecificationList.size()];
            //String[] idsArray = getSpecificationIdsArray(productInfo.getGoods_specification_ids());
            for (int i = 0;i<apiBookSpecificationList.size();i++){
                bookSepcifitionValue[i]  = apiBookSpecificationList.get(i).getValue();
                bookSepcifitionId[i] = apiBookSpecificationList.get(i).getId().toString();
            }

            cartInfo = new ApiCart();
            cartInfo.setBookId(bookId);
            cartInfo.setBookName(apiBook.getName());
            cartInfo.setListPicUrl(apiBook.getListPicUrl());
            cartInfo.setNumber(number);
            cartInfo.setUserId(loginUser.getUserId());
            cartInfo.setRetailPrice(apiBook.getUnitPrice());
            cartInfo.setMarketPrice(apiBook.getUnitPrice());
            cartInfo.setMarketPrice(apiBook.getUnitPrice());
            cartInfo.setChecked(1);
            if (null != bookSepcifitionValue) {
                cartInfo.setBookSpecifitionValueName(StringUtils.join(bookSepcifitionValue, ";"));
            }
            cartInfo.setBookSpecifitionIds(StringUtils.join(bookSepcifitionId, "_"));
            cartInfo.setChecked(1);
            apiCartService.save(cartInfo);
        } else {
            //如果已经存在购物车中，则数量增加
            if (apiBook.getStorage() < (number + cartInfo.getNumber())) {
                return this.toResponsObject(400, "库存不足", "");
            }
            cartInfo.setNumber(cartInfo.getNumber() + number);
            apiCartService.update(cartInfo);
        }
        return toResponsSuccess(bookCount(loginUser));
    }

}
